<template>
  <div class="alert-rule">
    <el-card shadow="hover" class="rule-card">
      <template #header>
        <div class="card-header">
          <span>告警规则配置</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">新增规则</el-button>
            <el-button @click="handleRefresh">刷新</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="规则名称">
            <el-input v-model="searchForm.name" placeholder="请输入规则名称" clearable />
          </el-form-item>
          <el-form-item label="告警类型">
            <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
              <el-option label="系统告警" value="system" />
              <el-option label="业务告警" value="business" />
              <el-option label="性能告警" value="performance" />
              <el-option label="安全告警" value="security" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" value="enabled" />
              <el-option label="禁用" value="disabled" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 规则列表 -->
      <el-table :data="ruleList" border v-loading="loading">
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" label="规则名称" min-width="150" />
        <el-table-column prop="type" label="告警类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getAlertTypeTag(row.type)">{{ getAlertTypeLabel(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="告警级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getAlertLevelTag(row.level)">{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="condition" label="触发条件" min-width="200" show-overflow-tooltip />
        <el-table-column prop="notifyType" label="通知方式" width="150">
          <template #default="{ row }">
            <el-tag v-for="type in row.notifyType.split(',')" :key="type" class="notify-tag">
              {{ getNotifyTypeLabel(type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="'enabled'"
              :inactive-value="'disabled'"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="primary" link @click="handleTest(row)">测试</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 规则表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增规则' : '编辑规则'"
      width="700px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        @submit.prevent
      >
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="告警类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%">
            <el-option label="系统告警" value="system" />
            <el-option label="业务告警" value="business" />
            <el-option label="性能告警" value="performance" />
            <el-option label="安全告警" value="security" />
          </el-select>
        </el-form-item>
        <el-form-item label="告警级别" prop="level">
          <el-select v-model="form.level" placeholder="请选择级别" style="width: 100%">
            <el-option label="严重" value="严重" />
            <el-option label="高" value="高" />
            <el-option label="中" value="中" />
            <el-option label="低" value="低" />
          </el-select>
        </el-form-item>
        <el-form-item label="触发条件" prop="condition">
          <el-input
            v-model="form.condition"
            type="textarea"
            :rows="3"
            placeholder="请输入触发条件（支持表达式）"
          />
        </el-form-item>
        <el-form-item label="通知方式" prop="notifyType">
          <el-select
            v-model="form.notifyType"
            multiple
            placeholder="请选择通知方式"
            style="width: 100%"
          >
            <el-option label="邮件" value="email" />
            <el-option label="短信" value="sms" />
            <el-option label="钉钉" value="dingtalk" />
            <el-option label="企业微信" value="wecom" />
            <el-option label="Webhook" value="webhook" />
          </el-select>
        </el-form-item>
        <el-form-item label="通知模板" prop="notifyTemplate">
          <el-input
            v-model="form.notifyTemplate"
            type="textarea"
            :rows="3"
            placeholder="请输入通知模板内容"
          />
          <div class="template-tips">
            <p>可用变量：</p>
            <el-tag v-for="templateVar in templateVars" :key="templateVar.key" class="template-var">
              {{ templateVar.label }}: {{ templateVar.key }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="静默期" prop="silencePeriod">
          <el-input-number
            v-model="form.silencePeriod"
            :min="0"
            :max="1440"
            :step="5"
            placeholder="请输入静默期（分钟）"
          />
          <span class="form-tip">设置为0表示不启用静默期</span>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="'enabled'"
            :inactive-value="'disabled'"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 测试结果对话框 -->
    <el-dialog
      v-model="testDialogVisible"
      title="规则测试结果"
      width="500px"
      destroy-on-close
    >
      <div class="test-result">
        <el-result
          :icon="testResult.success ? 'success' : 'error'"
          :title="testResult.success ? '测试通过' : '测试失败'"
          :sub-title="testResult.message"
        >
          <template #extra>
            <el-button @click="testDialogVisible = false">关闭</el-button>
          </template>
        </el-result>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAlertRuleList,
  addAlertRule,
  updateAlertRule,
  deleteAlertRule,
  testAlertRule
} from '@/api/message'

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: ''
})

// 列表数据
const ruleList = ref([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 表单对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  name: '',
  type: '',
  level: '',
  condition: '',
  notifyType: [],
  notifyTemplate: '',
  silencePeriod: 0,
  status: 'enabled',
  remark: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择告警类型', trigger: 'change' }],
  level: [{ required: true, message: '请选择告警级别', trigger: 'change' }],
  condition: [{ required: true, message: '请输入触发条件', trigger: 'blur' }],
  notifyType: [{ required: true, message: '请选择通知方式', trigger: 'change' }],
  notifyTemplate: [{ required: true, message: '请输入通知模板', trigger: 'blur' }]
}

// 通知模板变量
const templateVars = [
  { key: '${ruleName}', label: '规则名称' },
  { key: '${alertTime}', label: '告警时间' },
  { key: '${alertLevel}', label: '告警级别' },
  { key: '${alertType}', label: '告警类型' },
  { key: '${alertContent}', label: '告警内容' },
  { key: '${metricValue}', label: '指标值' },
  { key: '${threshold}', label: '阈值' }
]

// 测试结果对话框
const testDialogVisible = ref(false)
const testResult = reactive({
  success: false,
  message: ''
})

// 加载规则列表
const loadRuleList = async () => {
  try {
    loading.value = true
    const res = await getAlertRuleList({
      page: page.value,
      pageSize: pageSize.value,
      ...searchForm
    })
    ruleList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('加载规则列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  loadRuleList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 新增规则
const handleAdd = () => {
  dialogType.value = 'add'
  Object.keys(form).forEach(key => {
    form[key] = key === 'status' ? 'enabled' : key === 'notifyType' ? [] : key === 'silencePeriod' ? 0 : ''
  })
  dialogVisible.value = true
}

// 编辑规则
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(form).forEach(key => {
    form[key] = row[key]
  })
  form.notifyType = row.notifyType.split(',')
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = { ...form }
        submitData.notifyType = submitData.notifyType.join(',')
        if (dialogType.value === 'add') {
          await addAlertRule(submitData)
          ElMessage.success('新增规则成功')
        } else {
          await updateAlertRule(submitData)
          ElMessage.success('更新规则成功')
        }
        dialogVisible.value = false
        loadRuleList()
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '新增规则失败' : '更新规则失败')
      }
    }
  })
}

// 删除规则
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该规则吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteAlertRule(row.id)
      ElMessage.success('删除规则成功')
      loadRuleList()
    } catch (error) {
      ElMessage.error('删除规则失败')
    }
  })
}

// 测试规则
const handleTest = async (row) => {
  try {
    const res = await testAlertRule(row.id)
    testResult.success = res.data.success
    testResult.message = res.data.message
    testDialogVisible.value = true
  } catch (error) {
    ElMessage.error('测试规则失败')
  }
}

// 状态变更
const handleStatusChange = async (row) => {
  try {
    await updateAlertRule({
      id: row.id,
      status: row.status
    })
    ElMessage.success('状态更新成功')
  } catch (error) {
    row.status = row.status === 'enabled' ? 'disabled' : 'enabled'
    ElMessage.error('状态更新失败')
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  loadRuleList()
}

const handleCurrentChange = (val) => {
  page.value = val
  loadRuleList()
}

// 刷新
const handleRefresh = () => {
  loadRuleList()
}

// 工具方法
const getAlertTypeLabel = (type) => {
  const map = {
    system: '系统告警',
    business: '业务告警',
    performance: '性能告警',
    security: '安全告警'
  }
  return map[type] || type
}

const getAlertTypeTag = (type) => {
  const map = {
    system: 'danger',
    business: 'warning',
    performance: 'info',
    security: 'error'
  }
  return map[type] || 'info'
}

const getAlertLevelTag = (level) => {
  const map = {
    严重: 'danger',
    高: 'error',
    中: 'warning',
    低: 'info'
  }
  return map[level] || 'info'
}

const getNotifyTypeLabel = (type) => {
  const map = {
    email: '邮件',
    sms: '短信',
    dingtalk: '钉钉',
    wecom: '企业微信',
    webhook: 'Webhook'
  }
  return map[type] || type
}

// 初始化
onMounted(() => {
  loadRuleList()
})
</script>

<style lang="scss" scoped>
.alert-rule {
  padding: 20px;
  .rule-card {
    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
    .search-bar {
      margin-bottom: 20px;
    }
    .notify-tag {
      margin-right: 5px;
    }
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  .template-tips {
    margin-top: 10px;
    font-size: 12px;
    color: #909399;
    .template-var {
      margin: 5px 5px 0 0;
    }
  }
  .form-tip {
    margin-left: 10px;
    font-size: 12px;
    color: #909399;
  }
  .test-result {
    padding: 20px;
  }
}
</style> 